import { createRouter, createWebHashHistory } from 'vue-router';
import { getStorage } from '@/utils/tools'
import routes from "./routes";
import { useMenus } from '@/store'
import { ElMessage } from 'element-plus';
const router = createRouter({
    history: createWebHashHistory(),
    routes,
    scrollBehavior(to: any, from: any) {
        if (to.path !== from.path) {
            return { top: 0 };
        }
    },
});
router.beforeEach(async (to: any, from: any, next: any) => {
    // 判断是否需要登录才可以进入
    if (to.matched.some((_: any) => _.meta.auth)) {
        const token = getStorage('token')
        var permission = useMenus().getPermissionAction;
        if (token && token !== 'undefined' && permission != null) {
            if (to.path === '/login') {
                next({ path: '/' })
                return;
            }
            // console.log(permission)
            if ( useMenus().menus && permission === -1 || permission!.indexOf(to.meta.auth) > -1) {
                next()
            } else {
                ElMessage.error({
                    message: "无权限访问!"
                });
                return;
            }
        } else {
            next({
                name: 'login',
                query: {
                    redirect: to.fullPath
                }
            })
            localStorage.clear()
        }
    } else {
        next()
    }
})
export default router;